package com.clothing.customization.service.impl;

import com.clothing.customization.entity.CustomerOrder;
import com.clothing.customization.repository.OrderRepository;
import com.clothing.customization.service.OrderManagementService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单管理服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OrderManagementServiceImpl implements OrderManagementService {

    private final OrderRepository orderRepository;
    // TODO: 注入其他需要的Repository

    @Override
    public Map<String, Object> getOrderList(Integer status, Date startDate, Date endDate, String keyword, int page, int size) {
        // 创建分页请求
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createTime"));
        
        // 记录查询参数
        log.info("查询订单列表，参数：status={}, startDate={}, endDate={}, keyword={}, page={}, size={}", 
                status, startDate, endDate, keyword, page, size);
        
        // 查询订单列表
        Page<CustomerOrder> orderPage = orderRepository.findByConditions(status, startDate, endDate, keyword, pageable);
        
        // 记录查询结果
        log.info("查询到订单总数：{}，当前页数据量：{}", orderPage.getTotalElements(), orderPage.getContent().size());
        
        // 如果没有数据，生成测试数据
        if (orderPage.getTotalElements() == 0) {
            log.info("数据库中没有订单数据，生成测试数据");
            generateTestData();
            // 重新查询
            orderPage = orderRepository.findByConditions(status, startDate, endDate, keyword, pageable);
            log.info("重新查询后，订单总数：{}，当前页数据量：{}", orderPage.getTotalElements(), orderPage.getContent().size());
        }
        
        // 检查页码是否超出范围
        if (page >= orderPage.getTotalPages() && orderPage.getTotalPages() > 0) {
            log.warn("请求的页码 {} 超出了总页数 {}，将返回最后一页", page, orderPage.getTotalPages());
            // 重新查询最后一页
            pageable = PageRequest.of(orderPage.getTotalPages() - 1, size, Sort.by(Sort.Direction.DESC, "createTime"));
            orderPage = orderRepository.findByConditions(status, startDate, endDate, keyword, pageable);
            log.info("调整页码后，订单总数：{}，当前页数据量：{}", orderPage.getTotalElements(), orderPage.getContent().size());
        }
        
        // 转换订单数据
        List<Map<String, Object>> orders = orderPage.getContent().stream().map(order -> {
            Map<String, Object> orderMap = new HashMap<>();
            orderMap.put("id", order.getId());
            orderMap.put("orderNo", order.getOrderNo());
            orderMap.put("customerName", "客户" + order.getUserId()); // TODO: 从用户服务获取用户名
            orderMap.put("productName", order.getProductName());
            orderMap.put("amount", order.getFinalPrice() != null ? order.getFinalPrice() : order.getBudget());
            orderMap.put("status", order.getStatus());
            orderMap.put("createTime", order.getCreateTime());
            orderMap.put("deliveryDate", order.getDeliveryDate());
            orderMap.put("clothingType", order.getClothingType());
            orderMap.put("gender", order.getGender());
            return orderMap;
        }).collect(Collectors.toList());
        
        // 记录转换后的数据量
        log.info("转换后的订单数据量：{}", orders.size());
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("content", orders);
        result.put("totalElements", orderPage.getTotalElements());
        result.put("totalPages", orderPage.getTotalPages());
        result.put("size", orderPage.getSize());
        result.put("number", orderPage.getNumber());
        
        return result;
    }

    /**
     * 生成测试数据
     */
    @Transactional
    public void generateTestData() {
        String[] clothingTypes = {"衬衫", "西装", "裤子", "大衣", "连衣裙"};
        String[] genders = {"男", "女"};
        String[] styles = {"商务", "休闲", "正式", "运动"};
        String[] fabrics = {"棉", "羊毛", "丝绸", "麻", "涤纶"};
        String[] colors = {"黑色", "白色", "蓝色", "红色", "灰色", "棕色"};

        for (int i = 0; i < 50; i++) {
            CustomerOrder order = new CustomerOrder();
            order.setOrderNo("ORD" + System.currentTimeMillis() + i);
            order.setUserId((long)(i % 10 + 1)); // 10个用户
            order.setDesignerId((long)(i % 5 + 1)); // 5个设计师
            order.setProductName("定制" + clothingTypes[i % clothingTypes.length]);
            order.setClothingType(clothingTypes[i % clothingTypes.length]);
            order.setGender(genders[i % genders.length]);
            order.setSizeStandard("M");
            order.setFabric(fabrics[i % fabrics.length]);
            order.setColor(colors[i % colors.length]);
            order.setStyle(styles[i % styles.length]);
            order.setSpecialRequirements("希望有特殊设计");
            order.setBudget(new BigDecimal(100 + i * 10));
            order.setFinalPrice(new BigDecimal(120 + i * 10));

            // 设置创建时间为过去30天内
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -i % 30);
            order.setCreateTime(calendar.getTime());

            // 设置交付日期为未来30天内
            calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, i % 30);
            order.setDeliveryDate(calendar.getTime());

            order.setPaymentMethod("支付宝");
            order.setStatus(i % 6); // 0-5的状态
            order.setProgress(i % 100);

            orderRepository.save(order);
        }

        log.info("已生成50条测试订单数据");
    }

    @Override
    public Map<String, Object> getOrderDetail(Long id) {
        // 模拟订单详情
        Map<String, Object> orderDetail = new HashMap<>();
        orderDetail.put("id", id);
        orderDetail.put("orderNo", "ORD" + System.currentTimeMillis());
        orderDetail.put("customerName", "客户" + id);
        orderDetail.put("customerId", id * 10);
        orderDetail.put("designerName", "设计师" + id);
        orderDetail.put("designerId", id * 11);
        orderDetail.put("productName", "定制西装");
        orderDetail.put("clothingType", "西装");
        orderDetail.put("gender", "男");
        orderDetail.put("sizeStandard", "XL");
        orderDetail.put("fabric", "羊毛");
        orderDetail.put("color", "深蓝");
        orderDetail.put("style", "商务");
        orderDetail.put("specialRequirements", "希望袖口有特殊设计");
        orderDetail.put("budget", new BigDecimal("1200.00"));
        orderDetail.put("finalPrice", new BigDecimal("1500.00"));
        orderDetail.put("deliveryDate", new Date());
        orderDetail.put("paymentMethod", "支付宝");
        orderDetail.put("status", 2);
        orderDetail.put("progress", 60);
        orderDetail.put("createTime", new Date());
        orderDetail.put("paymentTime", new Date());

        List<Map<String, Object>> processLogs = getOrderProcessLogs(id);
        orderDetail.put("processLogs", processLogs);

        return orderDetail;
    }

    @Override
    @Transactional
    public boolean updateOrderStatus(Long id, Integer status, String remark) {
        try {
            // 检查订单是否存在
            CustomerOrder order = orderRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("订单不存在: " + id));
            
            // 更新订单状态
            order.setStatus(status);
            if (remark != null && !remark.isEmpty()) {
                order.setRemark(remark);
            }
            
            // 保存更新
            orderRepository.save(order);
            
            // 记录日志
            log.info("订单状态更新成功 - 订单ID: {}, 新状态: {}, 备注: {}", id, status, remark);
            
            return true;
        } catch (Exception e) {
            log.error("更新订单状态失败 - 订单ID: {}", id, e);
            throw new RuntimeException("更新订单状态失败: " + e.getMessage());
        }
    }

    @Override
    public List<Map<String, Object>> getOrderProcessLogs(Long orderId) {
        // 模拟流程记录
        List<Map<String, Object>> logs = new ArrayList<>();
        
        // 模拟数据
        String[] processTypes = {"下单", "支付", "设计确认", "生产", "发货", "完成"};
        for (int i = 0; i < processTypes.length; i++) {
            Map<String, Object> log = new HashMap<>();
            log.put("id", (long)(i + 1));
            log.put("orderId", orderId);
            log.put("processType", processTypes[i]);
            log.put("content", "订单" + processTypes[i] + "环节已完成");
            log.put("operatorName", "操作员" + (i + 1));
            log.put("operatorId", (long)(i + 1));
            
            // 设置时间为当前时间减去i天
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -i);
            log.put("createTime", calendar.getTime());
            
            // 只添加已完成的环节
            if (i < 4) {
                logs.add(log);
            }
        }
        
        // 按时间排序
        logs.sort(Comparator.comparing(log -> (Date) log.get("createTime")));
        
        return logs;
    }

    @Override
    @Transactional
    public boolean addOrderProcessLog(Long orderId, String processType, String content, Long operatorId) {
        // TODO: 实际实现添加流程记录的逻辑
        // 这里仅作模拟
        return true;
    }

    @Override
    public Map<String, Object> getOrderAnalysisData(String analysisType, Date startDate, Date endDate) {
        Map<String, Object> result = new HashMap<>();
        
        // 模拟数据
        List<Map<String, Object>> data = new ArrayList<>();
        List<String> categories = new ArrayList<>();
        
        switch (analysisType) {
            case "daily":
            case "weekly":
            case "monthly":
                // 时间维度分析
                SimpleDateFormat sdf = analysisType.equals("daily") ? 
                        new SimpleDateFormat("MM-dd") : 
                        analysisType.equals("weekly") ? 
                                new SimpleDateFormat("yyyy-ww周") : 
                                new SimpleDateFormat("yyyy-MM");
                
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(startDate);
                
                while (!calendar.getTime().after(endDate)) {
                    String dateStr = sdf.format(calendar.getTime());
                    categories.add(dateStr);
                    
                    Map<String, Object> item = new HashMap<>();
                    item.put("date", dateStr);
                    item.put("orderCount", new Random().nextInt(100) + 20);
                    item.put("totalAmount", new BigDecimal(new Random().nextInt(10000) + 1000));
                    item.put("averageAmount", new BigDecimal(new Random().nextInt(500) + 100));
                    
                    data.add(item);
                    
                    if (analysisType.equals("daily")) {
                        calendar.add(Calendar.DAY_OF_MONTH, 1);
                    } else if (analysisType.equals("weekly")) {
                        calendar.add(Calendar.WEEK_OF_YEAR, 1);
                    } else {
                        calendar.add(Calendar.MONTH, 1);
                    }
                }
                break;
                
            case "category":
                // 类别维度分析
                String[] categories1 = {"衬衫", "西装", "裤子", "大衣", "连衣裙"};
                for (String category : categories1) {
                    categories.add(category);
                    
                    Map<String, Object> item = new HashMap<>();
                    item.put("category", category);
                    item.put("orderCount", new Random().nextInt(100) + 20);
                    item.put("totalAmount", new BigDecimal(new Random().nextInt(10000) + 1000));
                    item.put("percentage", new Random().nextInt(30) + 10);
                    
                    data.add(item);
                }
                break;
                
            case "region":
                // 地区维度分析
                String[] regions = {"华东", "华南", "华北", "西南", "东北", "西北"};
                for (String region : regions) {
                    categories.add(region);
                    
                    Map<String, Object> item = new HashMap<>();
                    item.put("region", region);
                    item.put("orderCount", new Random().nextInt(100) + 20);
                    item.put("totalAmount", new BigDecimal(new Random().nextInt(10000) + 1000));
                    item.put("percentage", new Random().nextInt(30) + 10);
                    
                    data.add(item);
                }
                break;
        }
        
        result.put("categories", categories);
        result.put("data", data);
        
        return result;
    }

    @Override
    public Map<String, Object> getPendingDisputeList(int page, int size) {
        return getAllDisputeList("pending", page, size);
    }

    @Override
    public Map<String, Object> getAllDisputeList(String status, int page, int size) {
        // 模拟纠纷列表数据
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> disputes = new ArrayList<>();
        
        // 模拟数据
        for (int i = 0; i < size; i++) {
            Map<String, Object> dispute = new HashMap<>();
            dispute.put("id", (long)(i + 1));
            dispute.put("orderNo", "ORD" + System.currentTimeMillis() + i);
            dispute.put("customerName", "客户" + (i + 1));
            dispute.put("disputeType", i % 3 == 0 ? "质量问题" : i % 3 == 1 ? "发货延迟" : "退款纠纷");
            dispute.put("description", "客户反映" + (i % 3 == 0 ? "产品质量存在问题" : i % 3 == 1 ? "发货严重延迟" : "要求退款但未得到处理"));
            dispute.put("status", status != null ? status : (i % 4 == 0 ? "pending" : i % 4 == 1 ? "processing" : i % 4 == 2 ? "resolved" : "rejected"));
            dispute.put("createTime", new Date());
            
            // 如果状态不是pending，添加处理信息
            if (!"pending".equals(dispute.get("status"))) {
                dispute.put("processorName", "客服专员" + (i % 3 + 1));
                dispute.put("processorId", (long)(i % 3 + 1));
                dispute.put("processTime", new Date());
                
                if ("resolved".equals(dispute.get("status")) || "rejected".equals(dispute.get("status"))) {
                    dispute.put("resolution", "经核实，" + (i % 2 == 0 ? "同意" : "拒绝") + "客户的请求，" + 
                            (i % 2 == 0 ? "已安排重新制作/退款" : "因不符合条件，建议客户接受现有解决方案"));
                }
            }
            
            disputes.add(dispute);
        }
        
        result.put("content", disputes);
        result.put("totalElements", 50L);
        result.put("totalPages", 5);
        result.put("size", size);
        result.put("number", page);
        
        return result;
    }

    @Override
    public Map<String, Object> getDisputeDetail(Long id) {
        // 模拟纠纷详情
        Map<String, Object> dispute = new HashMap<>();
        dispute.put("id", id);
        dispute.put("orderNo", "ORD" + System.currentTimeMillis());
        dispute.put("orderId", id * 10);
        dispute.put("customerName", "客户" + id);
        dispute.put("customerId", id * 5);
        dispute.put("disputeType", "质量问题");
        dispute.put("description", "客户反映产品左侧袖口线头过多，且有轻微破损");
        dispute.put("evidenceImages", "image1.jpg,image2.jpg,image3.jpg");
        dispute.put("status", "processing");
        dispute.put("createTime", new Date());
        dispute.put("processorName", "客服专员1");
        dispute.put("processorId", 1L);
        dispute.put("processTime", new Date());
        
        // 模拟沟通记录
        List<Map<String, Object>> communicationLogs = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Map<String, Object> log = new HashMap<>();
            log.put("id", (long)(i + 1));
            log.put("disputeId", id);
            log.put("content", i % 2 == 0 ? 
                    "客服回复：您好，已收到您的反馈，我们会尽快处理，请耐心等待" :
                    "客户回复：好的，希望能尽快解决，谢谢");
            log.put("senderType", i % 2 == 0 ? "admin" : "customer");
            log.put("senderName", i % 2 == 0 ? "客服专员1" : "客户" + id);
            log.put("senderId", i % 2 == 0 ? 1L : id * 5);
            
            // 设置时间为当前时间减去(3-i)小时
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.HOUR, -(3-i));
            log.put("sendTime", calendar.getTime());
            
            communicationLogs.add(log);
        }
        
        dispute.put("communicationLogs", communicationLogs);
        
        // 获取相关订单详情
        Map<String, Object> orderInfo = getOrderDetail((Long) dispute.get("orderId"));
        dispute.put("orderInfo", orderInfo);
        
        return dispute;
    }

    @Override
    @Transactional
    public boolean processDispute(Long id, String status, String resolution, Long operatorId) {
        // TODO: 实际实现处理纠纷的逻辑
        // 这里仅作模拟
        return true;
    }

    @Override
    public Map<String, Object> getOrderStatistics() {
        // 模拟订单统计数据
        Map<String, Object> statistics = new HashMap<>();
        
        // 各状态订单数量
        Map<String, Integer> statusCounts = new HashMap<>();
        statusCounts.put("pendingPayment", 25);  // 待付款
        statusCounts.put("processing", 58);      // 处理中
        statusCounts.put("shipped", 37);         // 已发货
        statusCounts.put("completed", 156);      // 已完成
        statusCounts.put("cancelled", 18);       // 已取消
        statistics.put("statusCounts", statusCounts);
        
        // 订单总量和金额
        statistics.put("totalOrders", 294);
        statistics.put("totalAmount", new BigDecimal("352680.50"));
        
        // 当月数据
        statistics.put("monthlyOrders", 42);
        statistics.put("monthlyAmount", new BigDecimal("50420.25"));
        
        // 纠纷统计
        Map<String, Integer> disputeCounts = new HashMap<>();
        disputeCounts.put("pending", 8);        // 待处理
        disputeCounts.put("processing", 5);     // 处理中
        disputeCounts.put("resolved", 23);      // 已解决
        disputeCounts.put("rejected", 7);       // 已拒绝
        statistics.put("disputeCounts", disputeCounts);
        
        return statistics;
    }

    @Override
    public boolean deleteOrder(Long id) {
        try {
            // 检查订单是否存在
            CustomerOrder order = orderRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("订单不存在: " + id));
            
            // 检查订单状态，只允许删除特定状态的订单
            if (order.getStatus() != 0 && order.getStatus() != 5) {
                throw new RuntimeException("只能删除待付款或已取消的订单");
            }
            
            // 删除相关的流程记录
            // processLogRepository.deleteByOrderId(id);
            // 删除订单
            orderRepository.delete(order);
            
            return true;
        } catch (Exception e) {
            log.error("删除订单失败 - 订单ID: {}", id, e);
            throw new RuntimeException("删除订单失败: " + e.getMessage());
        }
    }
} 